import { readFileSync, readdirSync } from 'fs';

const svgTitle = /<svg([^>+].*?)>/;
const clearHeightWidth = /(width|height)="([^>+].*?)"/g;
const hasViewBox = /(viewBox="[^>+].*?")/g;
const clearReturn = /(\r)|(\n)/g;

// 创建symbol
function createSymbol(svg: string, id: string): never {
  const r = svg
    .replace(clearReturn, '')
    .replace(svgTitle, (_$1, $2) => {
      let width = 0;
      let height = 0;
      let content = $2.replace(clearHeightWidth, (_s1, s2, s3) => {
        if (s2 === 'width') width = s3;
        else if (s2 === 'height') height = s3;
        return '';
      });
      if (!hasViewBox.test($2)) content += `viewBox="0 0 ${width} ${height}"`;
      return `<symbol id="${id}" ${content}>`;
    })
    .replace('</svg>', '</symbol>');
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  return r;
}

function readSvgDirectory(path: string, directory: string, prefix: string): never[] {
  const arr: never[] = [];
  arr.push(...readSvg(path + directory + '/', prefix + '-' + directory));
  return arr;
}

// 查找svg文件
function readSvg(path: string, prefix: string): never[] {
  const arr = [];
  const direntArray = readdirSync(path, { withFileTypes: true });
  for (const dirent of direntArray) {
    if (dirent.isDirectory()) {
      arr.push(...readSvgDirectory(path, dirent.name, prefix));
    } else {
      console.log('读取', path, prefix + '-' + dirent.name.replace('.svg', ''));
      const svg = readFileSync(path + dirent.name).toString();
      arr.push(createSymbol(svg, prefix + '-' + dirent.name.replace('.svg', '')));
    }
  }
  return arr;
}

// 加载 svg
export const loadSvg = (path: string, prefix: string) => {
  if (path === '') return;
  console.log('读取 svg', path);
  const res = readSvg(path, prefix);
  return {
    name: 'svg-transform',
    transformIndexHtml(dom: string) {
      return dom.replace(
        '<body>',
        `<body><svg style="position:absolute; width:0; height:0; visibility:hidden" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >${res.join(
          ''
        )}</svg>`
      );
    }
  };
};
